#!c:/perl/bin/perl.exe
##########################################################################################################################
##### a script to add object permissions for Users of Wigan-Warriors.com
##########################################################################################################################

##########################################################################################################################
######  TODO list  #######################################################################################################
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
###### Bug list
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
# Includes
##########################################################################################################################

use lib qw(../cgi-bin);
use DBI;
use WiganRL;
use WiganRL::DataObject::Player;
use WiganRL::DataObject::Matchstats;
use WiganRL::DataObject::Squad;
use Getopt::Long;
use Term::ANSIColor qw(:constants);

use strict;
#use warnings;
local $SIG{__WARN__} = \&Carp::cluck;  #full call back trace

$|++;  #unbuffered

##########################################################################################################################
# get arguments
##########################################################################################################################

my $firstName;
my $lastName;
my $positionNames;
my $matchID;
my $forceInsert= 0;
 GetOptions ("fn=s" => \$firstName, 
"ln=s" => \$lastName, 
"position=s" => \$positionNames, 
"match=i" => \$matchID,
"fi" => \$forceInsert); # flag

print "Player: $firstName $lastName, Position: $positionNames, Debut: $matchID\n";

if ($lastName eq "") {
  print BOLD, "ERROR: No last name set\n", RESET;
  exit(1);
}

if ($matchID == 0) {
  print BOLD, "ERROR: No matchID set\n", RESET;
  exit(1);
}



##########################################################################################################################
# site setup and location variable declarations
##########################################################################################################################
my $cfg= WiganRL::DataObject->load_config('../cgi-bin/wiganrl.ini');

my $cgi= CGI::Simple->new();

my $dbh= Diva::DB->new();
$dbh->set( {
	DATABASE_NAME       => $cfg->val('database', 'DATABASE_NAME'),
	DATABASE_SERVER     => $cfg->val('database', 'DATABASE_SERVER'),
	DATABASE_USERNAME   => $cfg->val('database', 'DATABASE_USERNAME'),
	DATABASE_PASSWORD   => $cfg->val('database', 'DATABASE_PASSWORD'),
	DATABASE_TYPE       => $cfg->val('database', 'DATABASE_TYPE'),
	} );
$dbh->connect();
WiganRL::DataObject->dbh($dbh);
WiganRL::Search->dbh($dbh);
WiganRL::DataObject->init_class('WWCOM');  #loads contenttypes
WiganRL::DataObject->cgi($cgi);
WiganRL::DataObject->site_base_url('http://www.wiganwarriorsfans.com'.$cfg->val('paths', 'SITE_BASE_URL'));
WiganRL::DataObject->cgi_base_url('http://www.wiganwarriorsfans.com'.$cfg->val('paths', 'CGI_BASE_URL'));
WiganRL::DataObject->user(WiganRL::DataObject::User->new($cfg->val('site','SITE_ADMINUSER')));
WiganRL::DataObject->site_clubid($cfg->val('site', 'SITE_CLUBID'));

## load match

my $match= WiganRL::DataObject::Matchstats->new($matchID);
if (!$match->loaded) {
  print BOLD,"ERROR: debut match not found\n", RESET;
  exit(1);
}

print "Debut Match: ".$match->param('MATCHSTATS_RESULT')."\n";

## check player doesn't exist
if (!$forceInsert) {
  my $s= WiganRL::Search->new;
  $s->table('PLAYER');
  if ($firstName ne "") {
    $s->where("PLAYER_LASTNAME = '$lastName' AND PLAYER_FIRSTNAME = '$firstName'");

    my $results= $s->search;
    if ($#$results >= 0) {
      print BOLD, "ERROR: exact match player exists\n";
      print RED, WiganRL::DataObject->cgi_base_url."?s=Player\&o=".$results->[0]->id."\n", RESET;
      exit(1);
    }
  }

  $s->clear;
  $s->table('PLAYER');
  $s->where("(PLAYER_LASTNAME = '$lastName' OR PLAYER_FIRSTNAME = '$lastName')");
  my $results= $s->search;
  for my $p (@$results) {
    print "Surname match: ".$p->param('PLAYER_NAME')." - ".WiganRL::DataObject->cgi_base_url."?s=Player\&o=".$p->id."\n";
  }
  if ($#$results >= 0) {
    print BOLD, "ERROR: surname match players exist\n", RESET;
    exit(1); 
  }
}

##  create a new player
my $player= WiganRL::DataObject::Player->new();
$cgi->param('FK_CLUB_ID',WiganRL::DataObject->site_clubid);
$cgi->param('PLAYER_FIRSTNAME',$firstName);
$cgi->param('PLAYER_LASTNAME',$lastName);
if ($firstName ne "") {
  $cgi->param('PLAYER_FULLNAME',$firstName." ".$lastName);
} else {
  $cgi->param('PLAYER_FULLNAME',$lastName);
}
$cgi->param('PLAYER_NAME',$cgi->param('PLAYER_FULLNAME'));
$cgi->param('PLAYER_PROFILE',qq~$lastName made his debut against <a href="javascript:getObject('$matchID','MATCHSTATS');">~.
   $match->param('MATCHSTATS_OPPOSITION_CLUB_CLUB_NAME').qq~</a> on ~.$match->param('MATCH_KOTIME_FDATE').qq~ ~.$match->param('MATCH_KOTIME_YEAR').qq~\n~);
$cgi->param('PLAYER_DATEOFBIRTH','0000-00-00');

$player->update;
$player->update_savehistory(0);

$cgi->param('RELATEDOLD_IDS',$match->id);
$player->update_related;


print "New Player!\n`t";
print GREEN, WiganRL::DataObject->cgi_base_url."?s=Player\&o=".$player->id."\n", RESET;
print "Profile: ".$player->param('PLAYER_PROFILE')."\n";

## player positions
if ($positionNames ne "") {
  my @positionIDs;
  for my $pos (split(',',$positionNames)) {
    my $s= WiganRL::Search->new;
    $s->table('POSITION');
    $s->where("POSITION_NAME='$pos'");
    my $results= $s->search;
    if ($#$results == 0) {
      $positionIDs[$#positionIDs+1]= $results->[0]->id;
      print "Position: $pos has ID ".$results->[0]->id."\n";
    } else {
      print "Position: $pos not found\n";
    }
  }
  if ($#positionIDs >= 0) {
    $cgi->param('PLAYER_POSITIONS',@positionIDs);
    $player->update;
    print "Positions updated\n";
  } else {
    print BOLD,"** No positions added\n",RESET;
  }
}

## player signing
$cgi->delete('o');
$cgi->param('p',$player->id);
$cgi->param('PLAYERSIGNING_DATE',$match->param('MATCH_KOTIME'));
$cgi->param('PLAYERSIGNING_STATUS','Player');
$cgi->param('PLAYERSIGNING_NOTES',$player->param('PLAYER_PROFILE'));
$cgi->param('FK_CLUB_ID',WiganRL::DataObject->site_clubid);
$cgi->param('PLAYERSIGNING_LEAVEDATE','0000-00-00');

my $playerSigning= WiganRL::DataObject::Playersigning->new;
$playerSigning->update;

$cgi->param('RELATEDOLD_IDS',$match->id);
$playerSigning->update_related;

## squad player
my $squad= $match->squad('WIGAN');
my $squadplayer= WiganRL::DataObject::Squadplayer->new;
$cgi->param('FK_PLAYER_ID',$player->id);
$cgi->param('SQUADPLAYER_TYPE','Player');
$cgi->param('p',$squad->id);
$cgi->param('SQUAD_NUMBER','');
$squadplayer->update;

## team player
my $team= ($match->homesquad->club->id == $match->site_clubid) ? $match->team('HOME') : $match->team('AWAY');
my $teamplayer= WiganRL::DataObject::Teamplayer->new;
my $pos= 0;
for my $tp (@{$team->teamplayers}) {
  if ($pos>0 && !$tp->squadplayer->loaded) {
    $teamplayer= $tp;
    $cgi->param('TEAMPLAYER_POSITION',$tp->param('TEAMPLAYER_POSITION'));
    print "Found team position: ".$tp->param('TEAMPLAYER_POSITION')."\n";
    last;
  }
  $pos++;
}
if ($pos == $#{$team->teamplayers}+1) {
  $cgi->param('TEAMPLAYER_POSITION',$pos);
  print "No position available so adding new player at position: $pos\n";
}
$cgi->param('p',$team->id);
$cgi->param('FK_PLAYER_ID',$player->id);
$cgi->param('FK_SQUADPLAYER_ID',$squadplayer->id);
$cgi->param('TEAMPLAYER_SUBSTITUTE','False');
$teamplayer->update;

